package com.fishingwithme.android.ui.screens.harvest

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Map
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.ImageUploader
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.FishType
import com.fishingwithme.android.ui.viewmodels.HarvestViewModel
import kotlinx.coroutines.delay

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun AddHarvestScreen(
    navController: NavController,
    spotId: String? = null,
    viewModel: HarvestViewModel = hiltViewModel()
) {
    // Initialize the spot ID in the ViewModel if provided
    spotId?.let { viewModel.setSpotId(it) }

    val uiState by viewModel.uiState.collectAsState()
    LocalContext.current

    // State for fish selection popup
    var showFishSelection by remember { mutableStateOf(false) }

    // Automatically get location and spots when no spotId is provided
    LaunchedEffect(Unit) {
        if (spotId == null && uiState.spotId == null) {
            viewModel.getLocationAndSubmit()
        }
    }

    // Trigger search with debounce
    LaunchedEffect(uiState.searchQuery) {
        if (uiState.searchQuery.length > 1) {
            // Debounce search to avoid too many API calls
            delay(300)
            // Check if the query is still the same after delay
            viewModel.searchSpots()
        } else if (uiState.searchQuery.isEmpty()) {
            // Clear search results when query is empty
            viewModel.setSearchQuery("")
        }
    }

    Scaffold(
    ) { paddingValues ->

        if (uiState.isGettingLocation) {
            // Show loading indicator while getting location
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(AppDimensions.ICON_SIZE_48)
                )
                Text(
                    text = "正在快速获取位置和附近钓点...",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(top = AppDimensions.SPACING_16)
                )
                Text(
                    text = "请确保已开启GPS并处于户外开阔区域",
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(top = AppDimensions.SPACING_8)
                )
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(AppDimensions.SPACING_16),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_16)
            ) {
                // Image upload using ImageUploader component
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = stringResource(R.string.harvest_picture),
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            // Use the ImageUploader component
                            ImageUploader(
                                pictures = uiState.images,
                                onPicturesChanged = { images ->
                                    viewModel.updateImages(images)
                                },
                                maxImages = 6,
                                onImageUpload = { file ->
                                    // Use the ViewModel's upload method
                                    viewModel.uploadImage(file)
                                }
                            )
                        }
                    }
                }
                // Spot selection/search when no spot is provided
                if (spotId == null) {
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.primaryContainer
                            )
                        ) {
                            Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                                Text(
                                    text = stringResource(R.string.select_or_search_spot),
                                    style = MaterialTheme.typography.titleMedium,
                                    modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                                )

                                // Display selected spot info when available
                                uiState.spotId?.let { spotId ->
                                    Card(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(bottom = AppDimensions.SPACING_8),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                                        )
                                    ) {
                                        Column(modifier = Modifier.padding(AppDimensions.SPACING_12)) {
                                            Text(
                                                text = "已选择钓点: ${uiState.searchQuery}",
                                                style = MaterialTheme.typography.bodyLarge
                                            )
                                            Text(
                                                text = "如果这不是您想要的钓点，请使用下方按钮手动选择",
                                                style = MaterialTheme.typography.bodySmall,
                                                modifier = Modifier.padding(top = AppDimensions.SPACING_4)
                                            )
                                        }
                                    }
                                }

                                // Map selection button for manual spot selection
                                Button(
                                    onClick = { 
                                        // TODO: Implement map-based spot selection
                                        // This will be implemented later based on your requirements
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(bottom = AppDimensions.SPACING_8),
                                    enabled = !uiState.isGettingLocation
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Map,
                                        contentDescription = null,
                                        modifier = Modifier.padding(end = AppDimensions.SPACING_8)
                                    )
                                    Text("在地图上手动选择钓点")
                                }

                                // Location button to get precise location and spots
                                Button(
                                    onClick = { viewModel.getLocationAndSubmit() },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(bottom = AppDimensions.SPACING_8),
                                    enabled = !uiState.isGettingLocation
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.LocationOn,
                                        contentDescription = null,
                                        modifier = Modifier.padding(end = AppDimensions.SPACING_8)
                                    )
                                    Text(stringResource(R.string.get_precise_location))
                                }

                                // Search input field
                                OutlinedTextField(
                                    value = uiState.searchQuery,
                                    onValueChange = { query ->
                                        viewModel.setSearchQuery(query)
                                    },
                                    label = { Text(stringResource(R.string.search_spot)) },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(bottom = AppDimensions.SPACING_8),
                                    trailingIcon = {
                                        if (uiState.isSearching) {
                                            CircularProgressIndicator(
                                                modifier = Modifier.size(AppDimensions.ICON_SIZE_24),
                                                color = MaterialTheme.colorScheme.primary
                                            )
                                        }
                                    }
                                )

                                // Search results
                                if (uiState.searchResults.isNotEmpty()) {
                                    LazyColumn(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .heightIn(max = AppDimensions.CARD_HEIGHT_200)
                                            .padding(vertical = AppDimensions.SPACING_8),
                                        verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_4)
                                    ) {
                                        items(uiState.searchResults) { spot ->
                                            Card(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(vertical = AppDimensions.SPACING_2)
                                                    .clickable {
                                                        viewModel.selectSpot(spot.id, spot.name ?: "未知钓点")
                                                    },
                                                colors = CardDefaults.cardColors(
                                                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                                                )
                                            ) {
                                                Text(
                                                    text = spot.name ?: "未知钓点",
                                                    style = MaterialTheme.typography.bodyLarge,
                                                    modifier = Modifier.padding(AppDimensions.SPACING_12)
                                                )
                                            }
                                        }
                                    }
                                } else if (uiState.searchQuery.isNotEmpty() && !uiState.isSearching && uiState.searchResults.isEmpty()) {
                                    Text(
                                        text = stringResource(R.string.error_no_spots_found),
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.padding(top = AppDimensions.SPACING_8)
                                    )
                                }
                            }
                        }
                    }
                }
                // Harvest type selection
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = stringResource(R.string.harvest_type),
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            uiState.harvestTypes.forEach { type ->
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickable {
                                            viewModel.setHarvestType(type.code)
                                        }
                                        .padding(vertical = AppDimensions.SPACING_4),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    RadioButton(
                                        selected = type.checked,
                                        onClick = {
                                            viewModel.setHarvestType(type.code)
                                        }
                                    )
                                    Text(
                                        text = type.name,
                                        style = MaterialTheme.typography.bodyLarge,
                                        modifier = Modifier.padding(start = AppDimensions.SPACING_8)
                                    )
                                }
                            }
                        }
                    }
                }

                // Score selection
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = stringResource(R.string.score_label),
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            uiState.scores.forEach { score ->
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickable {
                                            viewModel.setScore(score.code)
                                        }
                                        .padding(vertical = AppDimensions.SPACING_4),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    RadioButton(
                                        selected = score.checked,
                                        onClick = {
                                            viewModel.setScore(score.code)
                                        }
                                    )
                                    Text(
                                        text = score.name,
                                        style = MaterialTheme.typography.bodyLarge,
                                        modifier = Modifier.padding(start = AppDimensions.SPACING_8)
                                    )
                                }
                            }
                        }
                    }
                }

                // Recommend checkbox
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { viewModel.toggleRec() }
                                .padding(AppDimensions.SPACING_16),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Checkbox(
                                checked = uiState.isRec,
                                onCheckedChange = { viewModel.toggleRec() }
                            )
                            Text(
                                text = stringResource(R.string.recommend),
                                style = MaterialTheme.typography.bodyLarge,
                                modifier = Modifier.padding(start = AppDimensions.SPACING_8)
                            )
                        }
                    }
                }

                // Fish selection
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable { showFishSelection = true },
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = stringResource(R.string.fish_species),
                                    style = MaterialTheme.typography.titleMedium
                                )
                                Icon(
                                    imageVector = Icons.Default.ArrowDropDown,
                                    contentDescription = stringResource(R.string.select_fish_type)
                                )
                            }

                            // Show selected fish types
                            FlowRow(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(top = AppDimensions.SPACING_8),
                                horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8)
                            ) {
                                uiState.fishTypes.filter { it.checked }.forEach { fish ->
                                    Card(
                                        modifier = Modifier.padding(AppDimensions.SPACING_4),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.secondaryContainer
                                        )
                                    ) {
                                        Text(
                                            text = fish.name,
                                            style = MaterialTheme.typography.bodySmall,
                                            modifier = Modifier.padding(AppDimensions.SPACING_8)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }


                // Comment input
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        OutlinedTextField(
                            value = uiState.comment,
                            onValueChange = { viewModel.setComment(it) },
                            label = { Text(stringResource(R.string.spot_description)) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16),
                            maxLines = 5
                        )
                    }
                }

                // Submit button
                item {
                    Button(
                        onClick = { viewModel.submitHarvest() },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(AppDimensions.BUTTON_HEIGHT_48),
                        enabled = !uiState.isLoading && uiState.spotId != null
                    ) {
                        if (uiState.isLoading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(AppDimensions.ICON_SIZE_24),
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text(
                                if (uiState.spotId == null) stringResource(R.string.spot_location) else stringResource(
                                    R.string.submit
                                )
                            )
                        }
                    }
                }

                // Error message
                item {
                    uiState.error?.let { errorMessage ->
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.errorContainer
                            )
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(AppDimensions.SPACING_16),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = errorMessage,
                                    color = MaterialTheme.colorScheme.onErrorContainer,
                                    modifier = Modifier.weight(1f)
                                )
                                Icon(
                                    imageVector = Icons.Default.Close,
                                    contentDescription = stringResource(R.string.close),
                                    tint = MaterialTheme.colorScheme.onErrorContainer,
                                    modifier = Modifier.clickable { viewModel.clearError() }
                                )
                            }
                        }
                    }
                }
            }
        }
    }

    // Fish selection popup
    if (showFishSelection) {
        FishSelectionPopup(
            fishTypes = uiState.fishTypes,
            onFishSelected = { code ->
                viewModel.toggleFishType(code)
            },
            onDismiss = { showFishSelection = false }
        )
    }

    // Handle success navigation
    if (uiState.isSuccess) {
        // Navigate back to the AnyBitting screen
        navController.navigate(FishingNavigation.ANYBITTING) {
            // Pop up to the AnyBitting screen and inclusive = false to keep it in the back stack
            popUpTo(FishingNavigation.ANYBITTING) { inclusive = true }
        }
    }
}

@Composable
fun FishSelectionPopup(
    fishTypes: List<FishType>,
    onFishSelected: (String) -> Unit,
    onDismiss: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppDimensions.SPACING_16),
        shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_16)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.select_fish_type),
                    style = MaterialTheme.typography.titleLarge
                )
                Icon(
                    imageVector = Icons.Default.Close,
                    contentDescription = "关闭",
                    modifier = Modifier.clickable { onDismiss() }
                )
            }

            Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))

            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8)
            ) {
                items(fishTypes) { fish ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onFishSelected(fish.code) }
                            .padding(vertical = AppDimensions.SPACING_8),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        if (fish.checked) {
                            Icon(
                                imageVector = Icons.Default.Check,
                                contentDescription = stringResource(R.string.selected),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        } else {
                            Spacer(modifier = Modifier.width(AppDimensions.ICON_SIZE_24))
                        }

                        Text(
                            text = fish.name,
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier
                                .padding(start = AppDimensions.SPACING_16)
                                .weight(1f)
                        )
                    }
                }
            }
        }
    }
}